package com.zsrt.devbase.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.zsrt.devbase.common.utils.StringUtil;
import com.zsrt.devbase.common.utils.mail.MailConfig;
import com.zsrt.devbase.common.utils.mail.SendMailHelper;
import com.zsrt.devbase.dto.EmailLogDTO;
import com.zsrt.devbase.service.SendMailService;

/** 
 * @author leixin  
 * @Email leixin821792669@gmail.com
 * @date 2018年7月7日 下午10:59:27
 * @version 1.0
 */
@Service("sendMailService")
public class SendMailServiceImpl implements SendMailService{
	//必填参数
	@Value("${email.formAddr}")
	private String formAddr;
	@Value("${email.host.name}")
	private String hostName ;
	@Value("${email.smtp.port}")
	private Integer smtpPort ;
	//选填参数
	@Value("${email.password}")
	private String password;
	@Value("${email.formName}")
	private String formName;
	@Value("${email.ssl.on.connect}")
	private Boolean sslOnConnect;
	@Value("${email.charset}")
	private String charSet;
	@Value("${email.use.appender}")
	private Boolean useAppender;
	@Value("${email.apperder}")
	private String mailAppender;
	@Autowired
	private FreeMarkerConfigurer freeMarker;
	
	private MailConfig config;

	@Override
	public List<EmailLogDTO> sendEmailBatch(List<EmailLogDTO> emailList) {
//		if (CollectionUtils.isEmpty(emailList)) {
//			return emailList;
//		}
		//创建n个线程的线程池
		int poolSize = 5;
		ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
		List<EmailLogDTO> resultList = new ArrayList<>();
		//设置循环次数
		int loopNum = emailList.size()/poolSize;
		FutureTask<EmailLogDTO> task = null;
		FutureTask<EmailLogDTO> isDoneTask = null;
 		List<FutureTask<EmailLogDTO>> taskList = null;
		for(int j = 0 ; j < loopNum + 1; j++ ) {
			taskList = new ArrayList<>();
			for(int k = 0 ; k < poolSize ; k ++ ) {
				int voloc = j * poolSize + k ;
				if (voloc >= emailList.size()) {
					break;
				}
				SendMailHelper mailHelper = new SendMailHelper.MailBuilder(emailList.get(voloc), useAppender, config).freeMarker(freeMarker).build();
				task = new FutureTask<>(mailHelper);
				threadPool.execute(task);
				taskList.add(task);
			}
				
			for(int i = 0 ; i < taskList.size(); i++) {
				isDoneTask = taskList.get(i);
				boolean isDone = Boolean.FALSE;
				//看任务有没有完成
				while (!isDone) {
					isDone = Boolean.TRUE;
					try {
						if (isDoneTask.isDone()) {
							resultList.add(isDoneTask.get());
						} else {
							isDone = Boolean.FALSE;
						}
					} catch (InterruptedException | ExecutionException e) {
						e.printStackTrace();
					} 
				}
			}
		}
		return resultList;
	}

	@Override
	public EmailLogDTO sendEmailSingle(EmailLogDTO dto) {
		SendMailHelper mailHelper = new SendMailHelper.MailBuilder(dto, useAppender, config).freeMarker(freeMarker).build();getClass();
		try {
			dto = mailHelper.call();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dto;
	}

	@PostConstruct
	public void initMailConfig() {
		this.config = new MailConfig.MailConfigBuilder(formAddr, hostName, smtpPort).password(password).build();
		if (!StringUtil.isEmpty(this.formName)) {
			this.config.setFormName(formName);
		}
		if (null != this.sslOnConnect) {
			this.config.setSslOnConnect(sslOnConnect);
		}
		if (!StringUtil.isEmpty(charSet)) {
			this.config.setCharSet(charSet);
		}
	}
	
}
